<?php

namespace api\modules\v1\controllers;

use common\business\EhrHelper;
use common\consts\StatusCodeEnum;
use common\helpers\StringUtil;
use common\models\kingdee\OrgAdmin;
use common\models\ResponseData;
use common\models\User;
use common\models\UserDepartment;
use yii\filters\auth\CompositeAuth;
use yii\filters\auth\QueryParamAuth;
use yii\filters\RateLimiter;
use yii\helpers\Json;
use yii\rest\ActiveController;
use yii\web\Response;
use Yii;

class DepartmentsController extends ActiveController
{
    public $modelClass = 'common\models\Department';

    public function behaviors() {
        $behaviors = parent::behaviors();

        $behaviors['rateLimiter'] = [
            'class' => RateLimiter::className(),
            'enableRateLimitHeaders' => true,
        ];

//        是否要验证
//        $behaviors['authenticator'] = [
//            'class' => CompositeAuth::className(),
//            'authMethods' => [
//                /*下面是三种验证access_token方式*/
//                //1.HTTP 基本认证: access token 当作用户名发送，应用在access token可安全存在API使用端的场景，例如，API使用端是运行在一台服务器上的程序。
//                //HttpBasicAuth::className(),
//                //2.OAuth 2: 使用者从认证服务器上获取基于OAuth2协议的access token，然后通过 HTTP Bearer Tokens 发送到API 服务器。
//                //HttpBearerAuth::className(),
//                //3.请求参数: access token 当作API URL请求参数发送，这种方式应主要用于JSONP请求，因为它不能使用HTTP头来发送access token
//                //http://localhost/user/index/index?access-token=123
//                QueryParamAuth::className(),
//            ],
//        ];

//        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    public function actions() {
        $actions = parent::actions();
        // 禁用""index,delete" 和 "create" 操作
        unset($actions['index'],$actions['delete'], $actions['create']);
        return $actions;
    }

//    public function actionIndex()
//    {
//        return $this->render('index');
//    }


    /**根据父节点的id拿到下一层的子节点
     * @param null $id
     * @return array
     */
    public function actionListByParent($id = null, $access_token = null){
//        $id = Yii::$app->request->post('id');
        $id = urldecode(stripslashes($id));
//        先定最外层的组织
        $TopOrg = OrgAdmin::findOne([
            'FPARENTID' => null,
        ]);
//        再根据access_token找到可见的最高层组织
        if (!StringUtil::isNullOrWhiteSpace($access_token)) {
            $user = User::findOne([
                'access_token' => $access_token,
            ]);
            if ($user){
                $userDept = UserDepartment::findOne([
                    'user_id' => $user->id
                ]);
                if ($userDept){
                    $deptNumber = $userDept->department_number;
                    $TopOrg = OrgAdmin::findOne([
                        'FNUMBER' => $deptNumber,
                    ]);
                }
            }
        }

        if (StringUtil::isNullOrWhiteSpace($id) || strtolower($id) == 'null' || strtolower($id) == 'undefined'){
            $topId = urlencode($TopOrg->FID);
            $item =  [
                'id' => $topId,
                'number' => $TopOrg->FNUMBER,
                'name' => $TopOrg->FNAME_L2,
                'layer' => EhrHelper::getOrgLayerTypeById($TopOrg->FLAYERTYPEID),
                'isParent' => true,
                'employee_num' => EhrHelper::getEmployeeCountUnderOrg($TopOrg->FID),
            ];

            return [
                'list' => [$item],
                'pre' => [
                    'id' => $topId,
                    'number' => $TopOrg->FNUMBER,
                    'name' => $TopOrg->FNAME_L2,
                ],
                'chain' => [
                    [
                        'id' => $topId,
                        'number' => $TopOrg->FNUMBER,
                        'name' => $TopOrg->FNAME_L2,
                    ]
                ],
            ];
        }

        $thisOrg = OrgAdmin::findOne([
            'FID' => $id,
        ]);
//        $childOrgs = OrgAdmin::findAll([
//            'FPARENTID' => $thisOrg->FID,
//        ]);
        $childOrgs = OrgAdmin::find()
            ->andFilterWhere([
                'FPARENTID' => $thisOrg->FID,
            ])
            ->orderBy([
                'FNUMBER' => SORT_ASC,
            ])->all();

        $orgArr = [];
        foreach ($childOrgs as $item){
            $child = OrgAdmin::findOne([
                'FPARENTID' => $item->FID,
            ]);
            $isParent = $child ? true : false;

            if (EhrHelper::OrgIsBelongToOther($item['FID'], $TopOrg->FID) || EhrHelper::OrgIsBelongToOther($TopOrg->FID, $item['FID'])){
                array_push($orgArr, [
                    'id' => urlencode($item['FID']),
                    'number' => $item['FNUMBER'],
                    'name' => $item['FNAME_L2'],
                    'layer' => EhrHelper::getOrgLayerTypeById($item['FLAYERTYPEID']),
                    'isParent' => $isParent,
                    'employee_num' => EhrHelper::getEmployeeCountUnderOrg($item['FID']),
                ]);
            }
        };

        $chain = EhrHelper::getOrgChain($id);

        $thisParent = OrgAdmin::findOne([
            'FID' => $thisOrg->FPARENTID
        ]);
        if (!$thisParent){
            $thisParent = $thisOrg;
        }

        return [
            'list' => $orgArr,
            'chain' => $chain,
            'pre' => [
                'id' => urlencode($thisParent->FID),
                'number' => $thisParent->FNUMBER,
                'name' => $thisParent->FNAME_L2,
            ],
        ];
    }


    public function actionGetOrgChain($id){

    }
}
